﻿Public Class Fabricante
    Private _indic As UInt16 = 1
    Private _nuevo As Boolean = False
    Private EnlaceTabla As New BindingSource
    Private cambios, notDataSaved As Boolean
    Private totalCampos As UInt16

    WriteOnly Property indic() As UInt16
        Set(ByVal Value As UInt16)
            _indic = Value
        End Set
    End Property

    WriteOnly Property nuevo() As Boolean
        Set(ByVal Value As Boolean)
            _nuevo = Value
        End Set
    End Property

    Private Sub Fabricantes_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim frm
        For Each frm In My.Application.OpenForms
            If frm.name = "ListaClientes" Then frm.refrescarDataGrid()
        Next
        frm = Nothing
        e.Cancel = notDataSaved
    End Sub

    Private Sub Fabricantes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim a, b, c, d, vp, incextra As NumberOnlyTextbox
        Dim sqlStr As String

        a = New NumberOnlyTextbox(Me.CCCAgencia, False, False, Nothing)
        b = New NumberOnlyTextbox(Me.CCCBanco, False, False, Nothing)
        c = New NumberOnlyTextbox(Me.CCCControl, False, False, Nothing)
        d = New NumberOnlyTextbox(Me.CCCCuenta, False, False, Nothing)
        vp = New NumberOnlyTextbox(Me.CliValorPunto, True, True, Nothing)
        incextra = New NumberOnlyTextbox(Me.TxtExtraIncr, False, False, Nothing)

        CmbExtraUni.SelectedIndex = 0
        CmbExtraApply.SelectedIndex = 0

        sqlStr = "SELECT [idFabricante],[Nombre],[Contacto],[NIF],[Direccion],[Poblacion]" & _
      ",[Provincia],[CP],[Pais],[Telefono],[Fax],[email],[Observaciones],[BancoNombre],[BancoDireccion]" & _
      ",[BancoAgencia],[CCCBanco],[CCCAgencia],[CCCControl],[CCCCuenta],CAST([ValorPunto] AS nvarchar(25)) AS [ValorPunto]" & _
      " FROM [furniture].[dbo].[Fabricantes] WHERE idFabricante = " & _indic.ToString
        If Not _nuevo Then EnlaceTabla.DataSource = _
            DataAccess.GetRecords(sqlStr, CommandType.Text)
        Enlaces()
        FillModelos()
        If Not _nuevo Then Extras()
    End Sub

    Private Sub FillModelos()
        'DB Extras => idExtra, idFabicante, Descripcion(txt), incremento, um(txt)
        Dim objeto As DataRowView
        Dim binding1 As New BindingSource
        binding1.DataSource = DataAccess.GetRecords("SELECT idModelo,Descripcion FROM Modelos WHERE idFab=" & _indic.ToString, CommandType.Text)
        If binding1.Count > 0 Then
            Dim i As Integer = 0
            LVModelos.Items.Clear()
            For i = 0 To binding1.Count - 1
                objeto = binding1.Item(i)
                Dim listItem As New ListViewItem(objeto.Item(0).ToString)
                listItem.SubItems.Add(objeto.Item(1).ToString)
                LVModelos.Items.Add(listItem)
                listItem = Nothing
            Next
            objeto = Nothing
            binding1 = Nothing
        End If
    End Sub

    Private Sub Extras()
        'DB Extras => idExtra, idFabicante, Descripcion(txt), incremento, um(txt)
        Dim objeto As DataRowView
        Dim binding1 As New BindingSource
        binding1.DataSource = DataAccess.GetRecords("SELECT Descripcion, incremento,um, CAST([applyTo] AS bit) FROM Extras WHERE idFabricante=" & _indic.ToString, CommandType.Text)
        If binding1.Count > 0 Then
            Dim i As Integer = 0
            For i = 0 To binding1.Count - 1
                objeto = binding1.Item(i)
                Dim listItem As New ListViewItem(objeto.Item(0).ToString)
                listItem.SubItems.Add(objeto.Item(2).ToString)
                listItem.SubItems.Add(IIf(objeto.Item(3), "Pedido", "Artículo"))
                ListView1.Items.Add(listItem)
                listItem = Nothing
            Next
        End If
    End Sub

    Private Sub cleanForm()
        Dim i As Integer

        For i = 0 To TabClient.TabPages.Count - 1
            For Each Objeto As Control In Me.TabClient.TabPages(i).Controls
                Objeto.DataBindings.Clear()
                If TypeOf Objeto Is TextBox Then Objeto.Text = ""
            Next
        Next
        For Each listitem As ListViewItem In ListView1.Items
            listitem.Remove()
        Next
        TabCliente.Select()
        CliNum.DataBindings.Clear()
        CliNum.Text = ""
        Enlaces()
    End Sub

    Private Sub Enlaces()
        Dim i As Integer
        totalCampos = 0
        For i = 0 To TabClient.TabPages.Count - 1
            TabClient.TabPages(i).Show()
            For Each Objeto As Control In Me.TabClient.TabPages(i).Controls
                If TypeOf Objeto Is TextBox And Objeto.Tag <> "!" Then
                    If Not _nuevo Then Objeto.DataBindings.Add("Text", EnlaceTabla, Objeto.Tag)
                    AddHandler Objeto.TextChanged, AddressOf Fabricantes_TextChanged
                    totalCampos += 1
                End If
            Next
        Next
        If Not _nuevo Then
            CliNum.DataBindings.Add("Text", EnlaceTabla, "idFabricante")
        End If

    End Sub

    Private Sub Fabricantes_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        cambios = True
        BtnClear.Enabled = IIf(_nuevo, True, False)
        BtnSave.Enabled = Convert.ToBoolean(CliName.Text.Length * sender.Text.Length * CliValorPunto.Text.Length)
    End Sub

    Private Sub ButnSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If cambios Then
            Dim msg = "¿Desea salir del módulo Fabricantes?"
            Dim title = "¡Advertencia!"
            Dim style = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or _
                        MsgBoxStyle.Critical
            notDataSaved = IIf(MsgBox(msg, style, title) = MsgBoxResult.Yes, False, True)
        End If
        Me.Close()
        If Not notDataSaved Then Me.Dispose()
    End Sub

    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        insertUpdate()
    End Sub

    Private Sub insertUpdate()
        Dim Valores(totalCampos) As String
        Dim Campos(totalCampos) As String
        Dim fabid As Integer
        Dim i As Integer
        Dim k As UInt16 = 0
        Dim procName As String = IIf(_nuevo, "insertFabricante", "updateFabricante")

        Campos.SetValue("@" + CliNum.Tag, k)
        Valores.SetValue(CliNum.Text, k)
        k += 1
        For i = 0 To TabClient.TabPages.Count - 1
            For Each Objeto As Control In Me.TabClient.TabPages(i).Controls
                If TypeOf Objeto Is TextBox And Objeto.Tag <> "!" Then
                    Campos.SetValue("@" + Objeto.Tag, k)
                    Valores.SetValue(Objeto.Text, k)
                    k += 1
                End If
            Next
        Next
        fabid = DataAccess.InsertNewRecord(Campos, Valores, procName)
        If fabid = -1 Then
            MessageBox.Show("Error al guardar registro de Fabricante")
        Else
            If Not _nuevo Then
                fabid = _indic
                If Not DataAccess.DeleteRecord("delExtras", fabid) Then MessageBox.Show("Error")
            End If
            ReDim Valores(4)
            ReDim Campos(4)
            Campos(0) = "@fabId"
            Campos(1) = "@descripcion"
            Campos(2) = "@incremento"
            Campos(3) = "@um"
            Campos(4) = "@applyTo"
            Valores(0) = fabid
            procName = "insertExtras"
            For i = 0 To ListView1.Items.Count - 1
                Valores(1) = ListView1.Items(i).Text
                Valores(2) = ListView1.Items(i).SubItems(1).Text
                Valores(3) = ListView1.Items(i).SubItems(2).Text
                Valores(4) = IIf(ListView1.Items(i).SubItems(3).Text = "Pedido", "1", "0")
                fabid = DataAccess.InsertNewRecord(Campos, Valores, procName)
            Next
            Erase Valores, Campos
            Select Case _nuevo
                Case True

                    cleanForm()
                Case False
                    notDataSaved = False
                    Me.Close()
                    Me.Dispose()
            End Select

        End If

    End Sub

    Private Sub BtnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClear.Click
        cleanForm()
    End Sub

    Private Sub TxtExtraDesc_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtExtraDesc.TextChanged
        BtnAddExtra.Enabled = Convert.ToBoolean(sender.text.length) And Convert.ToBoolean(TxtExtraIncr.Text.Length)
    End Sub

    Private Sub TxtExtraIncr_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtExtraIncr.TextChanged
        BtnAddExtra.Enabled = Convert.ToBoolean(sender.text.length) And Convert.ToBoolean(TxtExtraDesc.Text.Length)
    End Sub

    Private Sub BtnAddExtra_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAddExtra.Click
        Dim listItem As New ListViewItem(TxtExtraDesc.Text)
        listItem.SubItems.Add(TxtExtraIncr.Text)
        listItem.SubItems.Add(CmbExtraUni.Text)
        listItem.SubItems.Add(IIf(CmbExtraApply.SelectedIndex, "Pedido", "Artículo"))
        ListView1.Items.Add(listItem)
        listItem = Nothing
    End Sub

    Private Sub ListView1_ItemChecked(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckedEventArgs) Handles ListView1.ItemChecked
        Dim marca As Boolean = False
        For Each listitem As ListViewItem In ListView1.Items
            marca = marca Or listitem.Checked
        Next
        BtnDelExtra.Enabled = marca
    End Sub

    Private Sub BtnDelExtra_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDelExtra.Click
        For Each listitem As ListViewItem In ListView1.Items
            If listitem.Checked Then listitem.Remove()
        Next
        sender.Enabled = False
        BtnSave.Enabled = True
    End Sub

    Private Sub TxtModelo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtModelo.TextChanged
        Dim Txt As TextBox = sender
        BtnAddModelo.Enabled = Txt.Text.Length
    End Sub

    Private Sub LVModelos_ItemChecked(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckedEventArgs) Handles LVModelos.ItemChecked
        Dim marca As Boolean = False
        Dim lstView As ListView = sender
        For Each listitem As ListViewItem In lstView.Items
            marca = marca Or listitem.Checked
        Next
        BtnDelModelo.Enabled = marca
    End Sub

    Private Sub BtnDelModelo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDelModelo.Click
        For Each listitem As ListViewItem In LVModelos.Items
            If listitem.Checked Then
                listitem.Remove()
                DataAccess.DeleteRecord("delModelo", CInt(listitem.Text))
            End If
        Next
        sender.Enabled = False
    End Sub

    Private Sub BtnAddModelo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAddModelo.Click
        Dim Campos() As String = {"@fabId", "@descripcion"}
        Dim Valores() As String = {_indic.ToString, TxtModelo.Text}
        DataAccess.InsertNewRecord(Campos, Valores, "insertModelo")
        TxtModelo.Text = vbNullString
        FillModelos()
    End Sub
End Class